package com.jml.雪崩和穿透效应.service;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class RedisService {
	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	public void setObject(String key, Object value) {
		this.setObject(key, value, null);
	}

	public void setObject(String key, Object object, Long time) {
		// 存放String 类型
		if (object instanceof String) {
			setString(key, object);
		}
		// 存放 set类型
		if (object instanceof Set) {
			setSet(key, object);
		}

		if (object instanceof List) {
			// 存放list類型
			setList(key, object);
		}
		// 设置有效期 以秒为单位
		if(time!=null) {
			stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
		}
	}

	private void setList(String key, Object object) {
		List<String> listValue = (List<String>) object;
		for (String string : listValue) {
			stringRedisTemplate.opsForList().leftPush(key, string);
		}
	}

	public void setString(String key, Object object) {
		// 如果是String 类型
		String value = (String) object;
		stringRedisTemplate.opsForValue().set(key, value);
	}

	public void setSet(String key, Object object) {
		Set<String> value = (Set<String>) object;
		for (String oj : value) {
			stringRedisTemplate.opsForSet().add(key, oj);
		}
	}
	public void delKey(String key) {
		stringRedisTemplate.delete(key);
	}

	public String getString(String key) {
		return stringRedisTemplate.opsForValue().get(key);
	}

}

